package com.qdxwx.web.controller.ajax;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.book.BookService;
import com.qdxwx.models.book.Book;
import com.qdxwx.models.book.BookQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/ajax/book")
public class AjaxBookController {

    @Autowired
    private BookService bookService;

    @GetMapping("/get.json")
    @ResponseBody
    public AjaxResult view(HttpServletRequest request){
        int id = TKConvert.toInteger(request.getParameter("id"));
        if(id < 1) return AjaxResult.error("参数异常");
        Book book = bookService.get(id);
        if(book == null) return AjaxResult.error("找不到指定书籍");
        return AjaxResult.success(book);
    }


    @GetMapping("/list.json")
    @ResponseBody
    public AjaxResult list(HttpServletRequest request){
        int channelId = TKConvert.toInteger(request.getParameter("channelId"));
        Integer categoryId = TKConvert.toInteger(request.getParameter("categoryId"),null);
        Integer subjectId = TKConvert.toInteger(request.getParameter("subjectId"),null);
        Integer elite = TKConvert.toInteger(request.getParameter("elite"),null);
        Integer isTop = TKConvert.toInteger(request.getParameter("isTop"),null);
        Integer isHot = TKConvert.toInteger(request.getParameter("isHot"),null);
        Integer orderBy = TKConvert.toInteger(request.getParameter("orderBy"),0);
        Long userId = TKConvert.toLong(request.getParameter("userId"));
        int page = TKConvert.toInteger(request.getParameter("page"),1);
        int limit = TKConvert.toInteger(request.getParameter("limit"),5);
        BookQuery bookQuery = new BookQuery();
        bookQuery.setChannelId(channelId);
        bookQuery.setIsHot(isHot);
        bookQuery.setIsTop(isTop);
        bookQuery.setIsElite(elite);
        bookQuery.setSubjectId(subjectId);
        bookQuery.setCategoryId(categoryId);
        bookQuery.setOrderBy(orderBy);
        bookQuery.setIsAvailable(1);
        bookQuery.setUserId(userId);
        PageRequest pageRequest = new PageRequest();
        pageRequest.setCurrentPage(page);
        pageRequest.setPageSize(limit);
        List<Book> bookList = bookService.getList(bookQuery, pageRequest);
        return AjaxResult.success(bookList);
    }
}
